import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Image, ScrollView, Input, Button, Textarea } from '@tarojs/components';

import { assetsFileUrl } from '../../api/client';
import { userLoginLimit } from '../../contexts/store';
import DataErrorView from '../../components/dataError';
import EmptyContent from '../../components/emptyContent';
import DataLoadingView from '../../components/dataLoading';

import './index.scss';

// Taro在小程序平台使用View替代TouchableOpacity
const TouchableOpacity = View;

/**
 * 经验分享论坛页面
 * 用于用户之间分享驾驶学习经验和交流
 */
interface PostItem {
  id: string;
  title: string;
  content: string;
  author: {
    id: string;
    name: string;
    avatar: string;
    type: 'student' | 'coach';
  };
  tags: string[];
  likes: number;
  comments: number;
  views: number;
  createdAt: string;
  images?: string[];
}

interface CommentItem {
  id: string;
  postId: string;
  content: string;
  author: {
    id: string;
    name: string;
    avatar: string;
  };
  createdAt: string;
}

interface Category {
  id: string;
  name: string;
  icon?: string;
}

const ForumPage: React.FC = () => {
  // 状态管理
  const [posts, setPosts] = useState<PostItem[]>([]);
  const [filteredPosts, setFilteredPosts] = useState<PostItem[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [searchText, setSearchText] = useState<string>('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentPost, setCurrentPost] = useState<PostItem | null>(null);
  const [comments, setComments] = useState<CommentItem[]>([]);
  const [commentText, setCommentText] = useState<string>('');
  const [showCreateModal, setShowCreateModal] = useState<boolean>(false);
  const [newPostTitle, setNewPostTitle] = useState<string>('');
  const [newPostContent, setNewPostContent] = useState<string>('');
  const [newPostTags, setNewPostTags] = useState<string>('');

  const scrollViewRef = useRef<any>(null);
  const currentUser = {
    id: 'current-user',
    name: '我',
    avatar: assetsFileUrl('/profiles/f8d1f2.png'),
    type: 'student' as const
  };

  // 论坛分类
  const categories: Category[] = [
    { id: 'all', name: '全部' },
    { id: 'subject1', name: '科一' },
    { id: 'subject2', name: '科二' },
    { id: 'subject3', name: '科三' },
    { id: 'subject4', name: '科四' },
    { id: 'experience', name: '经验分享' },
    { id: 'coach', name: '教练心得' }
  ];

  /**
   * 加载帖子列表
   */
  const loadPosts = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // 模拟异步加载数据
      await new Promise(resolve => setTimeout(resolve, 800));
      
      // 模拟帖子数据
      const mockPosts: PostItem[] = [
        {
          id: '1',
          title: '科目二倒车入库技巧分享',
          content: '今天给大家分享一下我练习科目二倒车入库的心得。首先，一定要调整好后视镜的位置，然后记住关键点...',
          author: {
            id: 'user1',
            name: '小明同学',
            avatar: assetsFileUrl('/profiles/f8d1f2.png'),
            type: 'student'
          },
          tags: ['科目二', '倒车入库', '技巧'],
          likes: 128,
          comments: 32,
          views: 567,
          createdAt: '2023-09-15 10:00:00',
          images: [assetsFileUrl('/avatars/top-img-2.png'), assetsFileUrl('/avatars/top-img-3.png')]
        },
        {
          id: '2',
          title: '科目三路考注意事项总结',
          content: '刚考完科目三，一次性通过！分享一下我的经验。首先心态要放松，上车前一定要检查车况...',
          author: {
            id: 'user2',
            name: '考试小能手',
            avatar: assetsFileUrl('/avatars/top-img-4.png'),
            type: 'student'
          },
          tags: ['科目三', '路考', '注意事项'],
          likes: 96,
          comments: 24,
          views: 432,
          createdAt: '2023-09-14 16:30:00'
        },
        {
          id: '3',
          title: '教练分享：如何快速掌握离合器控制',
          content: '作为一名有10年教学经验的教练，我来分享一下离合器控制的技巧。首先，左脚要轻放在离合器踏板上...',
          author: {
            id: 'coach1',
            name: '张教练',
            avatar: assetsFileUrl('/avatars/top-img-5.png'),
            type: 'coach'
          },
          tags: ['教练心得', '离合器', '基础技巧'],
          likes: 189,
          comments: 45,
          views: 789,
          createdAt: '2023-09-13 09:15:00'
        },
        {
          id: '4',
          title: '科目一考试高频错题解析',
          content: '整理了科目一考试中容易出错的题目，希望能帮助大家顺利通过考试。第一题：在没有交通信号灯的路口...',
          author: {
            id: 'user3',
            name: '学霸笔记',
            avatar: assetsFileUrl('/avatars/top-img-6.png'),
            type: 'student'
          },
          tags: ['科目一', '错题解析', '考试技巧'],
          likes: 234,
          comments: 67,
          views: 1234,
          createdAt: '2023-09-12 14:20:00'
        },
        {
          id: '5',
          title: '科目四文明驾驶知识点汇总',
          content: '科目四主要考察文明驾驶和应急处理能力，这里汇总了重要的知识点...',
          author: {
            id: 'user4',
            name: '驾考',
            avatar: assetsFileUrl('/avatars/top-img-7.png'),
            type: 'student'
          },
          tags: ['科目四', '文明驾驶', '知识点'],
          likes: 156,
          comments: 38,
          views: 678,
          createdAt: '2023-09-11 11:45:00'
        }
      ];
      
      setPosts(mockPosts);
      setFilteredPosts(mockPosts);
    } catch (err) {
      setError('加载帖子列表失败，请稍后重试');
      console.error('Failed to load posts:', err);
    } finally {
      setLoading(false);
    }
  };

  /**
   * 加载帖子详情和评论
   */
  const loadPostDetail = async (postId: string) => {
    try {
      setLoading(true);
      setError(null);
      
      // 模拟加载帖子详情
      const post = posts.find(p => p.id === postId);
      if (post) {
        setCurrentPost(post);
        
        // 模拟加载评论
        await new Promise(resolve => setTimeout(resolve, 500));
        
        const mockComments: CommentItem[] = [
          {
            id: '1',
            postId: postId,
            content: '非常实用的技巧，我按照你的方法练习，果然有进步！',
            author: {
              id: 'user5',
              name: '练习生小王',
              avatar: assetsFileUrl('/avatars/top-img-8.png')
            },
            createdAt: '2023-09-15 11:30:00'
          },
          {
            id: '2',
            postId: postId,
            content: '请问后视镜的调整有什么具体的标准吗？',
            author: {
              id: 'user6',
              name: '新手司机',
              avatar: assetsFileUrl('/avatars/top-img-9.png')
            },
            createdAt: '2023-09-15 12:15:00'
          },
          {
            id: '3',
            postId: postId,
            content: '感谢分享，我明天就要考试了，希望能用上这些技巧！',
            author: {
              id: 'user7',
              name: '考试在即',
              avatar: assetsFileUrl('/avatars/top-img-10.png')
            },
            createdAt: '2023-09-15 13:45:00'
          }
        ];
        
        setComments(mockComments);
        setShowDetail(true);
      }
    } catch (err) {
      setError('加载帖子详情失败，请稍后重试');
      console.error('Failed to load post detail:', err);
    } finally {
      setLoading(false);
    }
  };

  /**
   * 筛选帖子
   */
  const filterPosts = (category: string, search: string) => {
    let result = posts;
    
    // 按分类筛选
    if (category !== 'all') {
      result = result.filter(post => 
        post.tags.some(tag => tag.includes(category)) || 
        category === 'experience'
      );
    }
    
    // 按搜索文本筛选
    if (search) {
      const lowerSearch = search.toLowerCase();
      result = result.filter(post => 
        post.title.toLowerCase().includes(lowerSearch) || 
        post.content.toLowerCase().includes(lowerSearch) || 
        post.tags.some(tag => tag.toLowerCase().includes(lowerSearch))
      );
    }
    
    setFilteredPosts(result);
  };

  /**
   * 处理分类选择
   */
  const handleCategoryChange = (categoryId: string) => {
    setSelectedCategory(categoryId);
    filterPosts(categoryId, searchText);
  };

  /**
   * 处理搜索
   */
  const handleSearch = (value: string) => {
    setSearchText(value);
    filterPosts(selectedCategory, value);
  };

  /**
   * 查看帖子详情
   */
  const handleViewPostDetail = (postId: string) => {
    loadPostDetail(postId);
  };

  /**
   * 返回帖子列表
   */
  const handleBackToList = () => {
    setShowDetail(false);
    setCurrentPost(null);
    setComments([]);
  };

  /**
   * 发送评论
   */
  const handleSendComment = () => {
    if (!commentText.trim() || !currentPost) return;
    
    const newComment: CommentItem = {
      id: Date.now().toString(),
      postId: currentPost.id,
      content: commentText.trim(),
      author: currentUser,
      createdAt: new Date().toLocaleString('zh-CN')
    };
    
    setComments(prevComments => [...prevComments, newComment]);
    setCommentText('');
    
    // 更新帖子评论数
    setPosts(prevPosts => 
      prevPosts.map(post => 
        post.id === currentPost.id 
          ? { ...post, comments: post.comments + 1 }
          : post
      )
    );
    
    if (currentPost) {
      setCurrentPost(prev => 
        prev ? { ...prev, comments: prev.comments + 1 } : null
      );
    }
  };

  /**
   * 点赞帖子
   */
  const handleLikePost = (postId: string) => {
    setPosts(prevPosts => 
      prevPosts.map(post => 
        post.id === postId 
          ? { ...post, likes: post.likes + 1 }
          : post
      )
    );
    
    if (currentPost && currentPost.id === postId) {
      setCurrentPost(prev => 
        prev ? { ...prev, likes: prev.likes + 1 } : null
      );
    }
  };

  /**
   * 创建新帖子
   */
  const handleCreatePost = () => {
    if (!newPostTitle.trim() || !newPostContent.trim()) {
      Taro.showToast({
        title: '标题和内容不能为空',
        icon: 'none'
      });
      return;
    }
    
    const tagsArray = newPostTags.split(',').map(tag => tag.trim()).filter(tag => tag);
    
    const newPost: PostItem = {
      id: Date.now().toString(),
      title: newPostTitle,
      content: newPostContent,
      author: currentUser,
      tags: tagsArray,
      likes: 0,
      comments: 0,
      views: 0,
      createdAt: new Date().toLocaleString('zh-CN')
    };
    
    setPosts(prevPosts => [newPost, ...prevPosts]);
    filterPosts(selectedCategory, searchText);
    
    // 重置表单并关闭模态框
    setNewPostTitle('');
    setNewPostContent('');
    setNewPostTags('');
    setShowCreateModal(false);
    
    Taro.showToast({
      title: '发布成功',
      icon: 'success'
    });
  };

  useEffect(() => {
    if(!userLoginLimit('获取当前分享，需登录服务')) return;
    loadPosts();
  }, []);

  /**
   * 格式化时间
   */
  const formatTime = (timeString: string) => {
    const date = new Date(timeString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    if (diff < 60000) { // 小于1分钟
      return '刚刚';
    } else if (diff < 3600000) { // 小于1小时
      return `${Math.floor(diff / 60000)}分钟前`;
    } else if (diff < 86400000) { // 小于1天
      return `${Math.floor(diff / 3600000)}小时前`;
    } else if (diff < 2592000000) { // 小于30天
      return `${Math.floor(diff / 86400000)}天前`;
    } else {
      return timeString;
    }
  };

  // 渲染帖子列表
  const renderPostList = () => {
    if (loading) {
      return (
        <DataLoadingView />
      );
    }
    
    if (error) {
      return (
        <DataErrorView content={error} onClickFunc={loadPosts} />
      );
    }
    
    if (filteredPosts.length === 0) {
      return (
        <View className="forum-empty-container">
          <Text className="forum-empty-text">暂无相关帖子</Text>
        </View>
      );
    }
    
    return (
      <View className="forum-post-list">
        {filteredPosts.map(post => (
          <View
            key={post.id}
            className="forum-post-item"
            onClick={() => handleViewPostDetail(post.id)}
          >
            <View className="forum-post-header">
              <Image src={post.author.avatar} className="forum-post-author-avatar" mode="aspectFill" />
              <View className="forum-post-author-info">
                <Text className="forum-post-author-name">{post.author.name}</Text>
                {post.author.type === 'coach' && (
                  <View className="forum-coach-badge">
                    <Text className="forum-coach-badge-text">教练</Text>
                  </View>
                )}
                <Text className="forum-post-time">{formatTime(post.createdAt)}</Text>
              </View>
            </View>
            
            <Text className="forum-post-title">{post.title}</Text>
            <Text className="forum-post-content">{post.content}</Text>
            
            {post.images && post.images.length > 0 && (
              <View className="forum-post-images">
                {post.images.map((img, index) => (
                  <Image key={index} src={img} className="forum-post-image" mode="aspectFill" />
                ))}
              </View>
            )}
            
            <View className="forum-post-tags">
              {post.tags.map((tag, index) => (
                <View key={index} className="forum-post-tag">
                  <Text className="forum-post-tag-text">{tag}</Text>
                </View>
              ))}
            </View>
            
            <View className="forum-post-stats">
              <View className="forum-stat-item">
                <MaterialIcons name="visibility" className="forum-stat-icon" color="#4b5cc4" size={16} />
                <Text className="forum-stat-text">{post.views}</Text>
              </View>
              <View className="forum-stat-item">
                <MaterialIcons name="favorite" className="forum-stat-icon" color="#ff3141" size={16} />
                <Text className="forum-stat-text">{post.likes}</Text>
              </View>
              <View className="forum-stat-item">
                <MaterialIcons name="comment" className="forum-stat-icon" color="#9ed900" size={16} />
                <Text className="forum-stat-text">{post.comments}</Text>
              </View>
            </View>
          </View>
        ))}
      </View>
    );
  };

  // 渲染帖子详情
  const renderPostDetail = () => {
    if (!currentPost) return null;
    
    if (loading) {
      return (
        <DataLoadingView />
      );
    }
    
    if (error) {
      return (
        <DataErrorView content={error} onClickFunc={() => loadPostDetail(currentPost.id)} />
      );
    }
    
    return (
      <View className="forum-post-detail">
        {/* 详情头部 */}
        <View className="forum-detail-header">
            <TouchableOpacity onClick={handleBackToList} className="forum-cur-back-button">
              <MaterialIcons name="arrow-back" className="forum-cur-back-icon" color="#333" size={16} />
            </TouchableOpacity>
            <Text className="forum-detail-title">帖子详情</Text>
            <View className="forum-header-right" />
        </View>
        
        {/* 帖子内容 */}
        <ScrollView className="forum-detail-content">
          <Text className="forum-detail-post-title">{currentPost.title}</Text>
          
          <View className="forum-detail-author-info">
            <Image src={currentPost.author.avatar} className="forum-detail-author-avatar" mode="aspectFill" />
            <View className="forum-author-details">
              <Text className="forum-detail-author-name">{currentPost.author.name}</Text>
              {currentPost.author.type === 'coach' && (
                <View className="forum-coach-badge">
                  <Text className="forum-coach-badge-text">教练</Text>
                </View>
              )}
              <Text className="forum-detail-post-time">{currentPost.createdAt}</Text>
            </View>
          </View>
          
          <Text className="forum-detail-post-content">{currentPost.content}</Text>
          
          {currentPost.images && currentPost.images.length > 0 && (
            <View className="forum-detail-post-images">
              {currentPost.images.map((img, index) => (
                <Image key={index} src={img} className="forum-detail-post-image" mode="aspectFill" />
              ))}
            </View>
          )}
          
          <View className="forum-detail-post-tags">
            {currentPost.tags.map((tag, index) => (
              <View key={index} className="forum-detail-post-tag">
                <Text className="forum-detail-post-tag-text">{tag}</Text>
              </View>
            ))}
          </View>
          
          <View className="forum-detail-post-stats">
            <TouchableOpacity className="forum-detail-stat-item" onClick={() => handleLikePost(currentPost.id)}>
              <MaterialIcons name="favorite" className="forum-detail-stat-icon" color="#ff3141" size={16} />
              <Text className="forum-detail-stat-text">{currentPost.likes}</Text>
              <Text className="forum-detail-stat-label">点赞</Text>
            </TouchableOpacity>
            <View className="forum-detail-stat-item">
              <MaterialIcons name="comment" className="forum-detail-stat-icon" color="#9ed900" size={16} />
              <Text className="forum-detail-stat-text">{currentPost.comments}</Text>
              <Text className="forum-detail-stat-label">评论</Text>
            </View>
            <View className="forum-detail-stat-item">
              <MaterialIcons name="visibility" className="forum-detail-stat-icon" color="#4b5cc4" size={16} />
              <Text className="forum-detail-stat-text">{currentPost.views}</Text>
              <Text className="forum-detail-stat-label">浏览</Text>
            </View>
          </View>
          
          {/* 评论区 */}
          <View className="forum-comments-section">
            <Text className="forum-comments-title">评论 ({comments.length})</Text>
            
            {comments.length === 0 ? (
              <Text className="forum-no-comments">暂无评论，快来抢沙发吧！</Text>
            ) : (
              comments.map(comment => (
                <View key={comment.id} className="forum-comment-item">
                  <Image src={comment.author.avatar} className="forum-comment-avatar" mode="aspectFill" />
                  <View className="forum-comment-content">
                    <View className="forum-comment-header">
                      <Text className="forum-comment-author">{comment.author.name}</Text>
                      <Text className="forum-comment-time">{formatTime(comment.createdAt)}</Text>
                    </View>
                    <Text className="forum-comment-text">{comment.content}</Text>
                  </View>
                </View>
              ))
            )}
          </View>
        </ScrollView>
        
        {/* 评论输入框 */}
        <View className="forum-comment-input-container">
          <Input
            className="forum-comment-input"
            value={commentText}
            onInput={(e) => setCommentText(e.detail.value)}
            placeholder="写下你的评论..."
            placeholderClass="forum-comment-input-placeholder"
          />
          <Button 
            className="forum-comment-send-button"
            type="primary"
            onClick={handleSendComment}
            disabled={!commentText.trim()}
          >
            发送
          </Button>
        </View>
      </View>
    );
  };

  // 渲染创建帖子模态框
  const renderCreateModal = () => {
    if (!showCreateModal) return null;
    
    return (
      <View className="forum-create-modal">
        <View className="forum-modal-overlay" onClick={() => setShowCreateModal(false)} />
        <View className="forum-modal-content">
          <View className="forum-modal-header">
            <Text className="forum-modal-title">发布新帖子</Text>
            <TouchableOpacity onClick={() => setShowCreateModal(false)} className="forum-modal-close">
              <Text className="forum-close-icon">×</Text>
            </TouchableOpacity>
          </View>
          
          <Input
            className="forum-modal-input"
            value={newPostTitle}
            onInput={(e) => setNewPostTitle(e.detail.value)}
            placeholder="请输入标题"
            placeholderClass="forum-modal-input-placeholder"
          />
          
          <Textarea
            className="forum-modal-textarea"
            value={newPostContent}
            onInput={(e) => setNewPostContent(e.detail.value)}
            placeholder="分享你的经验或问题..."
            placeholderClass="forum-modal-textarea-placeholder"
          />
          
          <Input
            className="forum-modal-input"
            value={newPostTags}
            onInput={(e) => setNewPostTags(e.detail.value)}
            placeholder="添加标签（用逗号分隔）"
            placeholderClass="forum-modal-input-placeholder"
          />
          
          <View className="forum-modal-actions">
            <Button 
              className="forum-modal-cancel-button"
              onClick={() => setShowCreateModal(false)}
            >
              取消
            </Button>
            <Button 
              className="forum-modal-confirm-button"
              type="primary"
              onClick={handleCreatePost}
            >
              发布
            </Button>
          </View>
        </View>
      </View>
    );
  };

  return (
    <View className="forum-page-container">
      {/* 帖子列表视图 */}
      {!showDetail ? (
        <View className="forum-container">
          {/* 页面头部 */}
          <View className="forum-header">
            <Text className="forum-title">圈子</Text>
            <TouchableOpacity 
              className="forum-create-button"
              onClick={() => setShowCreateModal(true)}
            >
              <Text className="forum-create-button-text">发布</Text>
            </TouchableOpacity>
          </View>
          
          {/* 搜索框 */}
          <View className="forum-search-container">
            <View className="forum-searchbar">
              <Input
                className="forum-search-input"
                placeholder="搜索帖子、经验、问题..."
                value={searchText}
                onInput={(e) => handleSearch(e.detail.value)}
                placeholderClass="forum-search-input-placeholder"
              />
            </View>
          </View>
          
          {/* 分类标签 */}
          <ScrollView 
            className="forum-categories-scrollview"
            horizontal
            showsHorizontalScrollIndicator={false}
          >
            <View className="forum-categories-container">
              {categories.map(category => (
                <TouchableOpacity
                  key={category.id}
                  className={`forum-category-item ${selectedCategory === category.id ? 'forum-selected' : ''}`}
                  onClick={() => handleCategoryChange(category.id)}
                >
                  <Text className={`forum-category-name ${selectedCategory === category.id ? 'forum-selected' : ''}`}>
                    {category.name}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>
          
          {/* 帖子列表 */}
          <ScrollView
            className="posts-scrollview"
            ref={scrollViewRef}
            scrollY
          >
            {renderPostList()}
          </ScrollView>
          
          {/* 创建帖子模态框 */}
          {renderCreateModal()}
        </View>
      ) : (
        // 帖子详情视图
        renderPostDetail()
      )}
    </View>
  );
};

export default ForumPage;